<?php

namespace app\api\controller;

use app\api\model\Wxapp as WxappModel;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\library\wechat\WxPay;
use think\Cache;
use think\Db;
use app\common\service\Order as OrderService;
use app\api\service\orderanswer\PaySuccess;
use app\common\enum\order\PayType as PayTypeEnum;

/** 地推类 */
class Ditui extends Controller
{
    /** 获取此次地推的积分 */
    public function getFen()
    {
        $paramArr = $this->request->param();
        $activeid = $paramArr['page_id'];
        $activeTitle = $paramArr['page_title'];
        $shop_id = $paramArr['shop_id'];
        $send_qaid = $paramArr['send_qaid'];
        $send_uid = $paramArr['send_uid'];
        $inline_fen = $paramArr['inline_fen'];
        $user_id = $paramArr['user_id'];


        if(!$activeid || !$activeTitle || !$shop_id || !$send_uid || !$user_id){
            return $this->renderError('缺少必要参数，无法领取');
        }
        if($send_uid==$user_id){
            return $this->renderError('不能自己参与自己的推广活动');
        }
        $dituiFen = 100;
        $kehuFen = $inline_fen-$dituiFen;

        //1. 判断赠送人是否是地推人员
        $dealerObj = Db::name('dealer_user')->where(['user_id'=>$send_uid])->find();
        if(!$dealerObj){
            return $this->renderError('地推人员无权限');
        }
        //2. 判断商户是否还有剩余积分，余额重复，进线记录入库，修改商户积分，商户积分日志入库
        $shopObj = Db::name('store_shop')->where(['shop_id'=>$shop_id])->find();
        $shopName = $shopObj['shop_name'];
        if($shopObj['shop_lastfen'] < $inline_fen){
            return $this->renderError('商家推广积分不足，无法领取');
        }

        //2. 判断此人是否领取了商家的本次推广活动，领取了几次
        $where = $send_qaid>0 ?
            "where dl_activeid=$activeid and dl_send_qaid=$send_qaid  and dl_userid=$user_id" :
            "where dl_activeid=$activeid and dl_send_qaid=0  and dl_userid=$user_id";
        $sql = "select count(0) as getNum from ".getTable('ditui_user')." ".$where;
        $res = Db::query($sql);
        $getNum = $res[0]['getNum'];
        //return $this->renderError('***'.$getNum);
        if($getNum > 0){
            return $this->renderError('您已经领取过了，不能重复领取');
        }

        $user = Db::name('user')->where('user_id', $user_id)->find();

        //如果没有找到此人的地推日志，则入库日志
        $inArr['dl_activeid'] = $activeid;
        $inArr['dl_activetitle'] = $activeTitle;
        $inArr['dl_shopid'] = $shop_id;
        $inArr['dl_shopname'] = $shopName;
        $inArr['dl_dituiuid'] = $send_uid;
        $inArr['dl_dituiname'] = $dealerObj['real_name'];
        $inArr['dl_dituimobile'] = $dealerObj['mobile'];
        $inArr['dl_allfen'] = $inline_fen;
        $inArr['dl_dituifen'] = $dituiFen;
        $inArr['dl_kehufen'] = $kehuFen;
        $inArr['dl_activeid'] = $activeid;
        $inArr['dl_userid'] = $user_id;
        $inArr['du_mobile'] = $user['true_mobile'];
        // dl_send_qaid可以看成是类型，0：代表光领取积分的类型，1：代表答题后领积分的类型
        $inArr['dl_send_qaid'] = $send_qaid>0 ? $send_qaid : 0;
        $inArr['dl_addtime'] = date('Y-m-d H:i:s',time());

        //如果此人已经在数据库中了，则修改为活动
        $inlineObj = Db::name('ditui_user')->where(['dl_userid'=>$user_id, 'dl_shopid'=>$shop_id])->find();
        if($inlineObj){
            Db::name('ditui_user')->where('dl_id',$inlineObj['dl_id'])->update($inArr);
        }
        //如果此人不在库中，则直接进线入库
        else{
            Db::name('ditui_user')->insert($inArr);
        }

        //note: 如果是答题挣积分，则走答题挣积分的逻辑
        if($shop_id>0 && $send_qaid>0 && $send_uid>0 && $user_id){
            //代表此时为答题进行推广
            return $this->getQaJifen($paramArr, $user);
        }

        //note: 如果是直接送积分的模式，则走以下模式
        return $this->getOnlyJifen($activeid,$activeTitle,$shop_id,$shopName,$send_uid,$inline_fen,$dituiFen,$kehuFen,$user_id);
    }

    /** 进线记录入库，修改商户积分，修改商户积分，商户余额日志入库 */
    private function getOnlyJifen($activeid,$activeTitle,$shop_id,$shopName,$send_uid,$inline_fen,$dituiFen,$kehuFen,$user_id){
        //修改商户积分，记录商户积分入库
        $sql33 = "update ".getTable('store_shop')." set shop_lastfen=shop_lastfen-$inline_fen where shop_id=".$shop_id;
        Db::query($sql33);
        $upArr111['jl_shopid'] = $shop_id;
        $upArr111['jl_shopname'] = $shopName;
        $upArr111['jl_type'] = 2;
        $upArr111['jl_dituiuid'] = $send_uid;
        $upArr111['jl_allfen'] = $inline_fen;
        $upArr111['jl_activeid'] = $activeid;
        $upArr111['jl_activetitle'] = $activeTitle;
        $upArr111['jl_describe'] = "地推活动扣除".$inline_fen."积分，地推奖励".$dituiFen."积分，客户奖励".$kehuFen."积分";
        $upArr111['jl_remark'] = $activeTitle."（扣除".$inline_fen."积分）";
        $upArr111['wxapp_id'] = $this->wxapp_id;
        $upArr111['jl_create_time'] = time();
        $upArr111['jl_create_timestr'] = date('Y-m-d H:i:s',time());
        Db::name('ditui_shop_jifenlog')->insert($upArr111);
        //4. 修改用户积分，积分记录入库
        $sql22 = "update ".getTable('user')." set points=points+$kehuFen , allsend_points=allsend_points+$kehuFen where user_id=".$user_id;
        Db::query($sql22);
        $upArr222['user_id'] = $user_id;
        $upArr222['value'] = $kehuFen;
        $upArr222['describe'] = "地推活动获得".$kehuFen."积分";
        $upArr222['remark'] = $activeTitle."（获得".$kehuFen."积分）";
        $upArr222['wxapp_id'] = $this->wxapp_id;
        $upArr222['create_time'] = time();
        Db::name('user_points_log')->insert($upArr222);
        //5. 地推人员余额变动，记录地推奖励日志
        $dituiMoney = floor($dituiFen/100);
        $sql33 = "update ".getTable('dealer_user')." set money=money+$dituiMoney where user_id=".$send_uid;
        Db::query($sql33);
        $inArr333['user_id'] = $user_id;
        $inArr333['scene'] = 80;
        $inArr333['money'] = $dituiMoney;
        $inArr333['pay_type'] = 2;
        $inArr333['mm_shopid'] = $shop_id;
        $inArr333['mm_shopname'] = $shopName;
        $inArr333['describe'] = "地推进线奖励".$dituiMoney."元";
        $inArr333['remark'] = $shopName."（进线奖励".$dituiMoney."元）";;
        $inArr333['wxapp_id'] = $this->wxapp_id;
        $inArr333['create_time'] = time();
        $inArr333['create_timestr'] = date('Y-m-d H:i:s',time());
        Db::name('user_balance_log')->insert($inArr333);
        //6. 返回地推人员推荐成功数据
        $userObj = Db::name('user')->where(['user_id'=>$user_id])->find();
        $back['state'] = 'getJfOk';
        $back['newPoints'] = $userObj['points'];
        $back['msg'] = '积分领取成功';
        return $this->renderSuccess(compact('back'));
    }

    /** 回答问题后获取积分 */
    private function getQaJifen($paramArr, $user){
        //1. 判断试卷是否存在，判断自己是否已经领取该试卷
        $qaid = $paramArr['send_qaid'];
        $user_id = $paramArr['user_id'];
        $senduid = $paramArr['send_uid'];
        $qaObj = Db::name('qa_boxquestion')->where(['bq_id'=>$qaid, 'wxapp_id'=>$this->wxapp_id])->find();
        if(!$qaObj){
            return $this->renderError('不存在该试卷');
        }

        // 2. 注销试卷的判断，因为该推广渠道已经做过了是否存在的判断
//        $buyObj = Db::name('qa_buyquestion')->where(['buy_qa_id'=>$qaid, 'buy_uid'=>$user_id])->find();
//        if($buyObj){
//            return $this->renderError('您已经领取过该问答了');
//        }

        $sendObj = Db::name('user')->where('user_id', $senduid)->find();

        $inArr['buy_uid'] = $user_id;
        $inArr['buy_unick'] = $user['nickName'];
        $inArr['buy_uheader'] = $user['avatarUrl'];
        $inArr['buy_qa_id'] = $qaid;
        $inArr['buy_qa_title'] = $qaObj['bq_title'];
        $inArr['buy_qa_price'] = $qaObj['bq_price'];
        $allJifen = ($qaObj['bq_price'] - $qaObj['bq_down_money']) * 100;
        $inArr['buy_alljifen'] = $allJifen;
        $inArr['buy_qa_des'] = $qaObj['bq_des'];
        $inArr['buy_easy'] = $qaObj['bq_easy'];
        $inArr['buy_qa_num'] = $qaObj['bq_num'];
        $inArr['wxapp_id'] = $this->wxapp_id;
        $inArr['buy_addtime_str'] = date('Y-m-d H:i:s',time());

        $inArr['from_uid'] = $sendObj['user_id'];
        $inArr['from_unick'] = $sendObj['nickName'];
        $inArr['from_uheader'] = $sendObj['avatarUrl'];
        $inArr['box_status'] = 5;

        $buyid = Db::name('qa_buyquestion')->insertGetId($inArr);

        $back['state'] = 'getQaOk';
        $back['qaid'] = $qaid;
        $back['buyid'] = $buyid;
        $back['msg'] = '问答领取成功';
        return $this->renderSuccess(compact('back'));
    }
}
